"""
@Author：Break
@Date：2023/05/09
@Links：https://www.cnbreak.org
@description：咸鱼之王答题助手
"""
import os, sys, time, shutil, win32gui, subject, logging
from PIL import ImageGrab
from paddleocr import PaddleOCR
from fuzzywuzzy import fuzz

# 初始化目录
img_dir = "img"  # 截图目录
if os.path.exists(img_dir):
    shutil.rmtree(img_dir)
os.makedirs(img_dir)
log_dir = "log"  # 日志目录
if os.path.exists(log_dir) == False:
    os.makedirs(log_dir)
# 定义时间格式
timeForFile = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
# 配置logging
logging.disable(logging.DEBUG)  # 关闭DEBUG日志的打印
# logging.disable(logging.WARNING)  # 关闭WARNING日志的打印
log_name = f"log/result_{timeForFile}.log"  # log文件名
handler = [logging.FileHandler(filename=log_name, encoding="utf-8")]  # 设置编码
logging.basicConfig(level=logging.INFO, handlers=handler)
# 获取指定窗体句柄
hwnd = win32gui.FindWindow(None, "咸鱼之王")
if hwnd == 0:
    print("未找到咸鱼之王窗口!")
    sys.exit()
else:
    print("咸鱼之王窗口句柄：", hwnd)
# 获取窗口位置和大小
left, top, right, bottom = win32gui.GetWindowRect(hwnd)


def run(left, top, right, bottom, num):
    # 截取窗口上部三分之一区域
    width = right - left
    top += 110
    height = int((bottom - top) / 3) - 120
    img = ImageGrab.grab((left, top, right, top + height))
    img_name = "img/xyzw" + str(num) + ".jpg"
    img.save(img_name)
    # OCR识别文字
    ocr = PaddleOCR(use_angle_cls=True, lang="ch")
    result = ocr.ocr(img_name, cls=True)
    # 输出结果
    text = ""
    for idx in range(len(result)):
        res = result[idx]
        for line in res:
            text += (line[1][0])

    # 计算内容相似度
    # 定义一个函数用来计算相似度并返回相似度最高的元素
    def find_most_similar(data, text):
        max_score = -1
        result = None
        for item in data:
            for key, value in item.items():
                score = fuzz.token_sort_ratio(text, value)
                if score > max_score:
                    max_score = score
                    result = item
        return result

    # 调用函数并打印结果
    result = most_similar = find_most_similar(subject.properties, text)
    print(time.strftime('%H:%M:%S', time.localtime(time.time())) + f"：|题目|{result['name']}  |结果|" + result["value"])
    # 记录日志,写入log
    logging.info(time.strftime('%H:%M:%S', time.localtime(time.time())) + f"：|ocr|{text}  |原题|{result['name']}  |结果|" + result["value"])


# 不停运行
num = 0
while True:
    # time.sleep(1)  # 时间间隔
    run(left, top, right, bottom, num)  # 主要工作函数
    num += 1
